import math
import random
import sys
import time
from datetime import datetime

from selenium.webdriver.common.by import By

from honey import honey_lands
from libs import config
from libs.action import WebDriverAction
from libs.cache import Cache
from libs.game import Game
from libs.image import ImageTool
from libs.log import Log
from libs.movement import Movement
from libs.task_helper import TaskHelper
from libs.trade_helper import TradeHelper
from libs.window import AdsWindow

if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Windmill')
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id
    log = Log(user_id)
    driver = AdsWindow(user_id).open(False)
    game = Game(driver, user_id)
    action = WebDriverAction(driver)
    movement = Movement(driver)
    image_tool = ImageTool(driver)
    trade_helper = TradeHelper(driver, user_id)
    account = config.get_account(user_id)
    cache = Cache()

    game.enter_game()
    game.collect_mail()
    game.snapshot(user_id, 'before windmill', include_skills=False)

    mill_items = {
        'grainbow_flour': {
            'name': 'Grainbow Flour',
            'sell_item_name': 'Grainbow Flour',
            'energy_cost': 23,
            'items': {
                'Grainbow': 1,
            },
            'wait_seconds': 33 * 60,
            'max_keep': 7
        },
        '4-leaf-colveregano': {
            'name': '4-Leaf Cloveregano',
            'sell_item_name': '4-Leaf Cloveregano',
            'energy_cost': 12,
            'items': {
                '4-Leaf Clover': 1 * 3,
                'Silk Slug Slime': 1 * 3,
            },
            'wait_seconds': 30 * 60,
            'max_keep': 7
        },
    }

    try:
        cooking_item_key = 'grainbow_flour'
        log.info(f'mill {cooking_item_key}')
        cooking_item = mill_items.get(cooking_item_key)
        energy_cost = cooking_item.get('energy_cost')
        buy_items = {}
        need_items = cooking_item.get('items', {})
        prepare = cooking_item.get('prepare', 1)
        for need_name in need_items:
            need_qty = need_items.get(need_name) * prepare
            has_qty = game.get_backpack_qty(need_name)
            if has_qty < need_qty:
                buy_items[need_name] = cooking_item.get('max_keep', 1) * need_qty - has_qty

        if len(buy_items) > 0:
            trade_helper.goto_buy_position()
            filter_input = trade_helper.open_market_buy()
            for buy_name in buy_items:
                buy_qty = buy_items.get(buy_name)
                trade_helper.market_buy_item(filter_input, buy_name, buy_qty)
            action.escape()
            action.escape()

        mill_loc = action.goto_mill()
        mill_x, mill_y = mill_loc
        action.click_by_offset(mill_x, mill_y)

        cooking_item_name = cooking_item.get('name')
        opt = action.find_element(By.XPATH, f"//span[text()='{cooking_item_name}']", cooking_item_name, 3)
        if opt is None:
            action.escape()
            time.sleep(1)
            action.click()
            opt = action.find_element(By.XPATH, f"//span[text()='{cooking_item_name}']", cooking_item_name, 10)
        opt.click()
        time.sleep(1)

        craft_button = action.find_element(By.CLASS_NAME, "Crafting_craftingButton__Qd6Ke", 'CraftButton', 2)

        if craft_button.text == 'Collect':
            if craft_button.is_enabled():
                craft_button.click()
                time.sleep(3)
                craft_button = action.find_element(By.CLASS_NAME, "Crafting_craftingButton__Qd6Ke", 'CraftButton', 2)

        if craft_button.text == 'Create':
            if craft_button.is_enabled():
                craft_button.click()
        action.escape()
        action.escape()

        sell_items = []
        for mill_item in mill_items.values():
            sell_name = mill_item.get('sell_item_name')
            max_keep = mill_item.get('max_keep', 1)
            has_qty = game.get_backpack_qty(sell_name)
            if has_qty >= max_keep:
                sell_items.append(sell_name)

        if len(sell_items) > 0:
            try:
                hour = datetime.now().hour
                if 9 < hour < 21:
                    action.goto_spec()
                    trade_helper.goto_sell_position()
                    for sell_item in sell_items:
                        trade_helper.open_shop_sell()
                        trade_helper.sell_item('Grainbow Flour', 111, price_delta=-1)
                        trade_helper.sell_item('4-Leaf Cloveregano', 111, price_delta=-1)
                        time.sleep(1)
                    action.escape()
                    action.escape()
            except Exception as e:
                log.info('sell error:' + str(e))
                pass

        game.snapshot(user_id, 'after willdmill', include_skills=False)
        task_helper.task_success()
        if account.get("honey") and game.get_energy() > 140 and not cache.get(f'honey_{user_id}_{next(iter(honey_lands))}'):
            task_helper.add_task('honey.py', delay_seconds=0)
            action.goto_spec()

        if user_id % 24 == datetime.now().hour:
            task_helper.windmill(delay_seconds=random.randint(6 * 60 * 60, 8 * 60 * 60))
        else:
            task_helper.windmill(delay_seconds=cooking_item.get('wait_seconds') + random.randint(30, 40))

    except Exception as e:
        task_helper.task_fail()
        task_helper.windmill(retry=True)
        raise e
